/**
 * Created by user on 2018/11/28.
 */
import React, { PureComponent } from 'react'
import { Layout, Menu, Icon } from 'antd'
import { Link } from 'dva/router'
import styles from './index.less'


const { Sider } = Layout
const { Item: MenuItem, SubMenu } = Menu

const getIcon = icon => {
  if (typeof icon === 'string') {
    if (icon.indexOf('http') === 0) {
      return <img src={icon} className={`${styles.icon} sider-menu-item-img`} alt="icon"/>
    }
    return <Icon type={icon}/>
  }
  return icon
}

class SiderMenu extends PureComponent {
  constructor(p) {
    super(p)
  }
  renderMenuItem() {
    const { menuData } = this.props
    let menus = menuData.map((menu, index) => this.getMenuItem(menu, index))
    return menus
  }
  getMenuItem(d) {
    const { location } = this.props
    let icon = getIcon(d.icon)
    if (d.children && d.children.length) {
      let subTitle = d.icon ? (
        <span>
          { getIcon(d.icon) }
          <span>{ d.name }</span>
        </span>
      ) : d.name
      return (
        <SubMenu key={ d.path } title={ subTitle }>
          { d.children.map(child => {
            return this.getMenuItem(child)
          }) }
        </SubMenu>
      )
    } else {
      return <MenuItem key={ d.path }>
        <Link
          to={d.path}
          replace={d.path === location.pathname}
        >
          { icon }
          <span>{ d.name }</span>
        </Link>
      </MenuItem>
    }
  }
  getSelectedKeys() {
    return []
  }
  render() {
    const { logo, location } = this.props
    let selectedKeys = this.getSelectedKeys()
    return (
      <Sider
        className={styles.sider}
        breakpoint="lg"
        collapsedWidth={100}
        width={256}
        onBreakpoint={(broken) => {
          //console.log(broken);
        }}
        onCollapse={(collapsed, type) => {
          //console.log(collapsed, type);
        }}
      >
        <div className={styles.logo} key="logo">
          <Link to="/" replace={'/' === location.pathname}>
            <img src={logo} alt="logo" />
            <h1>Ant Design Pro</h1>
          </Link>
        </div>
        <Menu theme="dark" mode="inline" selectedKeys={selectedKeys}>
          { this.renderMenuItem() }
        </Menu>
      </Sider>
    )
  }
}

export default SiderMenu
